import pygame, sys, random
from Unit import *
from Grid import *
from MotionType import *
from Landblock import *
from bredthFirstSearch import bredthFirstSearchStart
from pygame.locals import *

def update():
	#pygame.time.delay(100)
	fpsClock.tick(15)
	fps="%.2f" % fpsClock.get_fps()
	fpsSurfaceObj=fontObj.render(fps, False, pygame.Color(0,0,0))
	fpsRectobj =fpsSurfaceObj.get_rect()
	fpsRectobj.topleft=(screenWidth-(len(fps)*6),screenHeight-10)
	windowSurfaceObj.blit(fpsSurfaceObj,fpsRectobj)
	rowCol=''.join([str(selectedSquare[0]),',',str(selectedSquare[1])])
	rowColSurfaceObj=fontObj.render(rowCol, False, pygame.Color(0,0,0))
	rowColRectobj =rowColSurfaceObj.get_rect()
	rowColRectobj.topleft=((screenWidth-(len(fps)*6)-(len(rowCol)*6)),(screenHeight-10))
	windowSurfaceObj.blit(rowColSurfaceObj,rowColRectobj)
	currentTurnStr=''.join(['(',str(turnOrder[currentTurn]),')'])
	currentTurnSurfaceObj=fontObj.render(currentTurnStr, False, pygame.Color(0,0,0))
	currentTurnRectobj =currentTurnSurfaceObj.get_rect()
	currentTurnRectobj.topleft=((screenWidth-(len(fps)*6)-(len(rowCol)*6)-(len(currentTurnStr)*6)),(screenHeight-10))
	windowSurfaceObj.blit(currentTurnSurfaceObj,currentTurnRectobj)
	#print(str(fpsClock.get_fps()))
	pygame.display.update()
	return

pygame.init()
fpsClock = pygame.time.Clock()

screenWidth=800
screenHeight=640
#squareSize=80
squareSize=20

windowSurfaceObj = pygame.display.set_mode((screenWidth,screenHeight))
pygame.display.set_caption('Game')

newSurfaceObj = pygame.image.load('unknown.gif')
selected = pygame.image.load('selected.gif')
images={}
images['forest']={}
images['road']={}
images['mountain']={}
images['water']={}
images['plain']={}
images['HQ']={}
images['city']={}
images['reef']={}
images['airport']={}
images['base']={}
images['port']={}
images['forest']['regular']=pygame.image.load('forest.bmp')
images['road']['regular']=pygame.image.load('road.bmp')
images['mountain']['regular']=pygame.image.load('mountain.bmp')
images['water']['regular']=pygame.image.load('water.bmp')
images['plain']['regular']=pygame.image.load('plain.bmp')
images['HQ']['regular']=pygame.image.load('HQ.bmp')
images['city']['regular']=pygame.image.load('city.bmp')
images['reef']['regular']=pygame.image.load('reef.bmp')
images['airport']['regular']=pygame.image.load('airport.bmp')
images['base']['regular']=pygame.image.load('base.bmp')
images['port']['regular']=pygame.image.load('port.bmp')
images['forest']['highlight']=pygame.image.load('forest_highlight.bmp')
images['road']['highlight']=pygame.image.load('road_highlight.bmp')
images['mountain']['highlight']=pygame.image.load('mountain_highlight.bmp')
images['water']['highlight']=pygame.image.load('water_highlight.bmp')
images['plain']['highlight']=pygame.image.load('plain_highlight.bmp')
images['HQ']['highlight']=pygame.image.load('HQ_highlight.bmp')
images['city']['highlight']=pygame.image.load('city_highlight.bmp')
images['reef']['highlight']=pygame.image.load('reef_highlight.bmp')
images['airport']['highlight']=pygame.image.load('airport_highlight.bmp')
images['base']['highlight']=pygame.image.load('base_highlight.bmp')
images['port']['highlight']=pygame.image.load('port_highlight.bmp')
unitType='infantry'
#images['infantry']=pygame.image.load('infantry.png')
images['infantry']={}
images['infantry'][0]={}
images['infantry'][0]['unmoved']=pygame.image.load('infantry0.png')
images['infantry'][0]['moved']=pygame.image.load('infantry0moved.png')
images['infantry'][1]={}
images['infantry'][1]['unmoved']=pygame.image.load('infantry1.png')
images['infantry'][1]['moved']=pygame.image.load('infantry1moved.png')
images['infantry'][2]={}
images['infantry'][2]['unmoved']=pygame.image.load('infantry2.png')
images['infantry'][2]['moved']=pygame.image.load('infantry2moved.png')
images['infantry'][3]={}
images['infantry'][3]['unmoved']=pygame.image.load('infantry3.png')
images['infantry'][3]['moved']=pygame.image.load('infantry3moved.png')
infantryMotion=MotionType(unitType,{'HQ':1,'city':1,'base':1,'airport':1,'port':1,'shoal':1,'plain':1,'road':1,'mountain':2,'forest':2})
infantryMovement=4
infantryUnit=Unit(unitType,0,infantryMotion,infantryMovement)
unitType='mech'
images['mech']=pygame.image.load('mech.png')
mechMotion=MotionType(unitType,{'HQ':1,'city':1,'base':1,'airport':1,'port':1,'shoal':1,'plain':1,'road':1,'mountain':1,'forest':1})
mechMovement=2
mechUnit=Unit(unitType,0,mechMotion,mechMovement)
#------------------------------------ images['apc']=pygame.image.load('apc.png')
#------------------------ images['smallTank']=pygame.image.load('smallTank.png')
#---------------------- images['mediumTank']=pygame.image.load('mediumTank.png')
unitType='largeTank'
images[unitType]=pygame.image.load('largeTank.png')
largeTankMotion=MotionType(unitType,{'HQ':1,'city':1,'base':1,'airport':1,'port':1,'shoal':1,'plain':1,'road':1,'forest':2})
largeTankMovement=6
largeTankUnit=Unit(unitType,0,largeTankMotion,largeTankMovement)
#------------------------------ images['rocket']=pygame.image.load('rocket.png')
#---------------------------- images['missile']=pygame.image.load('missile.png')
#-------------------------------- images['recon']=pygame.image.load('recon.png')
#-------------------------------------- images['aa']=pygame.image.load('aa.png')
images['cat']=pygame.image.load('cat.png')
redColor = pygame.Color(255,0,0)
greenColor = pygame.Color(0,255,0)
blueColor = pygame.Color(0,0,255)
whiteColor = pygame.Color(255,255,255)
blackColor = pygame.Color(0,0,0)
mousex, mousey = 0,0

fontObj = pygame.font.Font('freesansbold.ttf',10)
msg = 'Hello world!'
#print(msg);

#soundObj = pygame.mixer.Sound('bounce.wav')
#pygame.draw.polygon(windowSurfaceObj, greenColor, ((146,0), (291,106), (236,277),(56, 277), (0,106)))
#colors = [pygame.Color(random.randint(0,255),random.randint(0,255),random.randint(0,255)),pygame.Color(random.randint(0,255),random.randint(0,255),random.randint(0,255)),pygame.Color(random.randint(0,255),random.randint(0,255),random.randint(0,255)),pygame.Color(random.randint(0,255),random.randint(0,255),random.randint(0,255))]

grid=Grid('map2.map')
prePlacedUnits=grid.getPrePlacedUnits()
for unit in prePlacedUnits:
	unitSplit=unit.split(',')
	row=int(unitSplit[0])
	column=int(unitSplit[1])
	unitTypeChar=unitSplit[2]
	team=int(unitSplit[3])
	if(unitTypeChar=='i'):
		grid.getCell(row,column).setUnit(Unit('infantry',team,infantryMotion,infantryMovement))
	else:
		print(''.join(['Unknown unit type: ',unitTypeChar]))
	
#print(str(grid))
#cells=grid.getCells()

selectedSquare=(0,0)
selectedUnit=False
selectedUnitSquareRow=0
selectedUnitSquareColumn=0
movementSquares=None

turnOrder=[1,3,0,2]
currentTurn=0

focus='grid'
focusedMenu=None
startingHeight=0
validMenuButtons=(0,0,0) #mv,fya,end
currentMenuButton=0

#grid.getCell(0,0).setUnit(mechUnit)
#grid.getCell(10,10).setUnit(largeTankUnit)
#grid.getCell(14,14).setUnit(infantryUnit)
#grid.getCell(15,15).setUnit(mechUnit)

#update()

while True:
	windowSurfaceObj.fill(whiteColor)
	for row in range(grid.getRows()):
		for column in range(grid.getColumns()):
			cell=grid.getCell(row,column)
			rowPos=row*squareSize
			columnPos=column*squareSize
			if((rowPos<screenWidth) and (columnPos<screenHeight)):
				imageType=str(cell.getlType())
				imageSecondary=str(cell.getSecondary())
				image=images[imageType][imageSecondary]
				image=pygame.transform.scale(image,(squareSize,squareSize))
				windowSurfaceObj.blit(image,(columnPos,rowPos))
				if(cell.getUnit()!=None):
					unit=cell.getUnit()
					unitType=unit.getType()
					unitTeam=unit.getTeam()
					unitState=unit.getState()
					unitImage=images[unitType][unitTeam][unitState]
					unitImage=pygame.transform.scale(unitImage,(squareSize,squareSize))
					windowSurfaceObj.blit(unitImage,(columnPos,rowPos))
					if((selectedUnit) and ((selectedUnitSquareColumn,selectedUnitSquareRow)== (column,row))):
						for square in movementSquares:
							grid.getCell(square[0],square[1]).setSecondary('highlight')
	if(focus=='grid'):
		selected2=pygame.transform.scale(selected,(squareSize,squareSize))
		selectedRowPos=selectedSquare[0]*squareSize
		selectedColumnPos=selectedSquare[1]*squareSize
		windowSurfaceObj.blit(selected2,(selectedColumnPos,selectedRowPos))
	elif(focus=='menu'):
		if(focusedMenu!=None):
			if(focusedMenu=='SingleMenu'):
				mvValid=validMenuButtons[0]
				moveText="mv"
				moveSurfaceObj=fontObj.render(moveText, False, pygame.Color(0,0,0))
				moveSurfaceObj=pygame.transform.scale(moveSurfaceObj,(squareSize,squareSize));
				moveRectobj =moveSurfaceObj.get_rect()
				moveRectobj.topleft=(screenWidth-squareSize,startingHeight)
				windowSurfaceObj.blit(moveSurfaceObj,moveRectobj)
				fyaValid=validMenuButtons[1]
				fyaText="fya"
				fyaSurfaceObj=fontObj.render(fyaText, False, pygame.Color(0,0,0))
				fyaSurfaceObj=pygame.transform.scale(fyaSurfaceObj,(squareSize,squareSize));
				fyaRectobj =fyaSurfaceObj.get_rect()
				fyaRectobj.topleft=(screenWidth-squareSize,squareSize+startingHeight)
				windowSurfaceObj.blit(fyaSurfaceObj,fyaRectobj)
				endValid=validMenuButtons[2]
				endText="end"
				endSurfaceObj=fontObj.render(endText, False, pygame.Color(0,0,0))
				endSurfaceObj=pygame.transform.scale(endSurfaceObj,(squareSize,squareSize));
				endRectobj =endSurfaceObj.get_rect()
				endRectobj.topleft=(screenWidth-squareSize,squareSize*2+startingHeight)
				windowSurfaceObj.blit(endSurfaceObj,endRectobj)
				selected2=pygame.transform.scale(selected,(squareSize,squareSize))
				if(currentMenuButton==0):
					windowSurfaceObj.blit(selected2,(screenWidth-squareSize,startingHeight))
				elif(currentMenuButton==1):
					windowSurfaceObj.blit(selected2,(screenWidth-squareSize,squareSize+startingHeight))
				elif(currentMenuButton==2):
					windowSurfaceObj.blit(selected2,(screenWidth-squareSize,squareSize*2+startingHeight))
	for event in pygame.event.get():
		if event.type == QUIT:
			pygame.quit()
			sys.exit()
		elif event.type == MOUSEMOTION:
			mousex, mousey = event.pos
			x=int(mousex/squareSize)
			y=int(mousey/squareSize)
			if((y,x)!=selectedSquare):
				if((0<=x<grid.getColumns()) and (0<=y<grid.getRows())):
					pass #selectedSquare=(y,x)
		elif event.type == MOUSEBUTTONUP:
			mousex, mousey = event.pos
			if event.button==1: #2 middle, 3 right, 4 scroll up, 5 scroll down
				x=int(mousex/squareSize)
				y=int(mousey/squareSize)
				if((y,x)!=selectedSquare):
					if((0<=x<grid.getColumns()) and (0<=y<grid.getRows())):
						pass #selectedSquare=(y,x)
				else:
					pass #pygame.event.post(pygame.event.Event(KEYDOWN,{'key':K_RETURN}))
		elif event.type == KEYDOWN:
			if event.key == K_ESCAPE:
				pygame.event.post(pygame.event.Event(QUIT))
			if event.key == K_RETURN:
				if(focus=='grid'):
					print(''.join(['Grid: Enter']))
					y,x=selectedSquare
					if(not selectedUnit):
						if((grid.getCell(y,x).getUnit()!=None) and (grid.getCell(y,x).getUnit().getTeam()==turnOrder[currentTurn]) and (grid.getCell(y,x).getUnit().getState()!='moved')):
							selectedUnit=True
							selectedUnitSquareRow=y
							selectedUnitSquareColumn=x
							movementSquares=bredthFirstSearchStart(grid, grid.getCell(y,x).getUnit(), y, x)
						else:
							print(''.join(['Grid: Bringing Up Menu']))
							focus='menu'
							focusedMenu='SingleMenu'
							startingHeight=0								
							validMenuButtons=(0,0,1) #mv,fya,end
							currentMenuButton=2
					else:
						if(grid.getCell(y,x).getUnit()==None):
							if(grid.getCell(y,x).getSecondary()=='highlight'):
								print(''.join(['Grid: Bringing Up Menu']))
								focus='menu'
								focusedMenu='SingleMenu'
								startingHeight=0								
								validMenuButtons=(1,0,0) #mv,fya,end
								currentMenuButton=0
								#selectedUnit=False
								#moveUnit=grid.getCell(selectedUnitSquareRow,selectedUnitSquareColumn).getUnit()
								#grid.getCell(selectedUnitSquareRow,selectedUnitSquareColumn).setUnit(None)
								#grid.getCell(y,x).setUnit(moveUnit)
								#grid.getCell(y,x).getUnit().setState('moved')
							else:
								selectedUnit=False
						for row in range(0,grid.getRows()):
							for column in range(0,grid.getColumns()):
								grid.getCell(row,column).setSecondary('regular')
				elif(focus=='menu'):
					print(''.join(['Menu: Enter']))
					if(focusedMenu==None):
						print(''.join(['Error: No FocusMenu with menu as focus']))
					elif(focusedMenu=='SingleMenu'):
						if(validMenuButtons[currentMenuButton]==1):
							if(currentMenuButton==0):
								print(''.join(['Menu: Moving Unit']))
								selectedUnit=False
								moveUnit=grid.getCell(selectedUnitSquareRow,selectedUnitSquareColumn).getUnit()
								grid.getCell(selectedUnitSquareRow,selectedUnitSquareColumn).setUnit(None)
								grid.getCell(y,x).setUnit(moveUnit)
								grid.getCell(y,x).getUnit().setState('moved')
								for row in range(0,grid.getRows()):
									for column in range(0,grid.getColumns()):
										grid.getCell(row,column).setSecondary('regular')
								print(''.join(['Menu: Grid now focused']))
								focus='grid'
								focusedMenu=None
								startingHeight=0
								validMenuButtons=(0,0,0)
								currentMenuButton=0
							elif(currentMenuButton==2):
								currentTurn=currentTurn+1
								if(currentTurn==len(turnOrder)):
									currentTurn=0
								for row in range(grid.getRows()):
									for col in range(grid.getColumns()):
										if((grid.getCell(row,col).getUnit()!=None) and (grid.getCell(row,col).getUnit().getTeam()==turnOrder[currentTurn])):
											grid.getCell(row,col).getUnit().setState('unmoved')
								print(''.join(['Menu: Grid now focused']))
								focus='grid'
								focusedMenu=None
								startingHeight=0
								validMenuButtons=(0,0,0)
								currentMenuButton=0
			if event.key == K_BACKSPACE:
				if(focus=='menu'):
					print(''.join(['Menu: Backspace']))
					print(''.join(['Menu: Grid now focused']))
					focus='grid'
					focusedMenu=None
					startingHeight=0
					validMenuButtons=(0,0,0)
					currentMenuButton=0
			if event.key == K_q:
				pass
				#msg = 'zoom in'
				#print(msg)
				#if(squareSize<100):
				#	squareSize+=10
			if event.key==K_e:
				pass
				#msg = 'zoom out'
				#print(msg)
				#if(squareSize>20):
				#	squareSize-=10
			if event.key==K_m:
				currentTurn=currentTurn+1
				if(currentTurn==len(turnOrder)):
					currentTurn=0
				for row in range(grid.getRows()):
					for col in range(grid.getColumns()):
						if((grid.getCell(row,col).getUnit()!=None) and (grid.getCell(row,col).getUnit().getTeam()==turnOrder[currentTurn])):
							grid.getCell(row,col).getUnit().setState('unmoved')
			if event.key==K_p:
				randRow=random.randint(0,grid.getRows()-1)
				randColumn=random.randint(0,grid.getColumns()-1)
				randTeam=random.randint(0,3)
				grid.getCell(randRow,randColumn).setUnit(Unit('cat',randTeam,MotionType('ground'),15))
			if event.key == K_LEFT:
				if(focus=='grid'):
					print(''.join(['Grid: Selected Square Left']))
					if(selectedSquare[1]>0):
						selectedSquare=(selectedSquare[0],selectedSquare[1]-1)
				elif(focus=='menu'):
					print(''.join(['Menu: Left']))
					if(focusedMenu==None):
						print(''.join(['Error: No FocusMenu with menu as focus']))
					elif(focusedMenu=='SingleMenu'):
						pass
			if event.key == K_RIGHT:
				if(focus=='grid'):
					print(''.join(['Grid: Selected Square Right']))
					if(selectedSquare[1]<(grid.getColumns()-1)):
						selectedSquare=(selectedSquare[0],selectedSquare[1]+1)
				elif(focus=='menu'):
					print(''.join(['Menu: Right']))
					if(focusedMenu==None):
						print(''.join(['Error: No FocusMenu with menu as focus']))
					elif(focusedMenu=='SingleMenu'):
						pass
			if event.key == K_UP:
				if(focus=='grid'):
					print(''.join(['Grid: Selected Square Up']))
					if(selectedSquare[0]>0):
						selectedSquare=(selectedSquare[0]-1,selectedSquare[1])
				elif(focus=='menu'):
					print(''.join(['Menu: Up']))
					if(focusedMenu==None):
						print(''.join(['Error: No FocusMenu with menu as focus']))
					elif(focusedMenu=='SingleMenu'):
						currentMenuButton=currentMenuButton-1
						if(currentMenuButton<0):
							currentMenuButton=len(validMenuButtons)-1
			if event.key == K_DOWN:
				if(focus=='grid'):
					print(''.join(['Grid: Selected Square Down']))
					if(selectedSquare[0]<(grid.getColumns()-1)):
						selectedSquare=(selectedSquare[0]+1,selectedSquare[1])
				elif(focus=='menu'):
					print(''.join(['Menu: Down']))
					if(focusedMenu==None):
						print(''.join(['Error: No FocusMenu with menu as focus']))
					elif(focusedMenu=='SingleMenu'):
						currentMenuButton=currentMenuButton+1
						if(currentMenuButton==len(validMenuButtons)):
							currentMenuButton=0
	update()
